﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using crm_dal.Objects;
using System.ServiceModel;
using System.Configuration;
using core_services.WCF.SalesReport;
using crm_services.WCF.SalesReport;
using crm_library.Controls.CompoundControls;

namespace crm_web.ReportPages
{
	public partial class SalesReports : System.Web.UI.Page
	{
		#region service class
		private static class Service
		{
			private static string ServiceURL
			{
				get
				{
					return "http://localhost:51940/WCF/SalesReport/SalesReport.svc";
				}
			}

			private static ChannelFactory<ISalesReport> _factory;
			private static ChannelFactory<ISalesReport> Factory
			{
				get
				{
					if (_factory == null)
					{
						var ep = new EndpointAddress(ServiceURL);
						_factory = new ChannelFactory<ISalesReport>(new BasicHttpBinding(), ep);
					}
					return _factory;
				}
			}

			private static ISalesReport Client
			{
				get
				{
					return Factory.CreateChannel();
				}
			}

			public static SalesReportResponse GetResponse(DateTime start, DateTime end, int userID)
			{
				SalesReportFilter filter = new SalesReportFilter
												{
													From = start,
													To = end,
													UserID = userID
												};
				return Client.GenerateSalesReport(filter);
			}
		}
		#endregion service class

		#region controls
		private DropDownList Users;
		private DateChooser StartDate;
		private DateChooser EndDate;
		private Button RunReport;
		#endregion controls

		#region properties
		private DateTime ReportStartDate
		{
			get
			{
				return DateTime.Parse(StartDate.Value);
			}
		}
		private DateTime ReportEndDate
		{
			get
			{
				return DateTime.Parse(EndDate.Value);
			}
		}
		private int UserID
		{
			get
			{
				return int.Parse(Users.SelectedValue);
			}
		}
		#endregion properties

		#region lifecycle
		public void Page_Init(object sender, EventArgs e)
		{
			InitControls();




		}


		private void InitControls()
		{
			var earliest = new DateTime(2000, 01, 01);
			var latest = DateTime.Today;

			var UsersPane = new Panel
								{
									CssClass = "CtrlPanel"
								};

			Users = new DropDownList
			{
				ID = "UserId_DDL",
				ClientIDMode = ClientIDMode.Static
			};

			Users.Items.Add(new ListItem("All", "-1"));
			Users.Items.AddRange( crm_dal.Objects.User.GetAll().Select( user => user.ToListItem() ).ToArray());

			var StartPane = new Panel
								{
									CssClass = "CtrlPanel"
								};

			StartDate = new DateChooser(earliest, latest, DateChooser.StartingValues.Earliest)
			{
				ID = "StartDate_DateChooser",
				ClientIDMode = ClientIDMode.Static,
				Layout = DateChooser.DateChooserLayoutType.Simple,
				RenderFilter = DateChooser.DateChooserRenderFilter.AllControls,
				LabelText = "From: "
			};

			var EndPane = new Panel
			{
				CssClass = "CtrlPanel"
			};

			EndDate = new DateChooser(earliest.AddDays(1), latest.AddDays(1), DateChooser.StartingValues.Latest)
			{
				ID = "EndDate_DateChooser",
				ClientIDMode = ClientIDMode.Static,
				Layout = DateChooser.DateChooserLayoutType.Simple,
				RenderFilter = DateChooser.DateChooserRenderFilter.AllControls,
				LabelText = "To: "
			};

			if (!IsPostBack)
			{
				Users.SelectedValue = "-1";
			}


			RunReport = new Button
			{
				ID = "RunReport_Btn",
				ClientIDMode = System.Web.UI.ClientIDMode.Static,
				Text = "Run Report",
				CommandName = "RunReport",
				CommandArgument = "RunReport"
			};
			RunReport.Command += RunReport_Command;

			UsersPane.Controls.Add(new Literal { Text = "User: " });
			UsersPane.Controls.Add(Users);
			StartPane.Controls.Add(StartDate);
			EndPane.Controls.Add(EndDate);

			ReportContents.Controls.Add(UsersPane);
			ReportContents.Controls.Add(StartPane);
			ReportContents.Controls.Add(EndPane);

			ReportContents.Controls.Add(RunReport);
		}
		#endregion lifecycle


		#region events
		void RunReport_Command(object sender, CommandEventArgs e)
		{
			GenerateSalesReport();
		}
		#endregion events


		private void GenerateSalesReport()
		{
			var response = Service.GetResponse(ReportStartDate, ReportEndDate, UserID);
			List<Sale> sales = response.Contents.ToList();

			var table = new Table();
			table.ID = "sortMe";
			table.ClientIDMode = System.Web.UI.ClientIDMode.Static;
			table.CssClass = "SortableTable tablesorter";

			var userNameLabel = GenerateLiteral("Selling Agent");
			var customerLabel = GenerateLiteral("Customer");
			var totalLabel = GenerateLiteral("Sale Total");
			table.Rows.Add(GenerateTableRow(TableRowSection.TableHeader, userNameLabel, customerLabel, totalLabel));

			var totalSales = 0.0M;
			foreach (var sale in sales)
			{
				var userName = GenerateLiteral(sale.UserName);
				var clientName = GenerateLiteral(sale.ClientName);
				var total = GenerateLiteral(sale.TotalStr.ToString());

				table.Rows.Add(GenerateTableRow(TableRowSection.TableBody, userName, clientName, total));

				totalSales += sale.Total;
			}

			var empty = GenerateLiteral("");
			var finalTotal = GenerateLiteral( String.Format("{0:C}", totalSales));


			table.Rows.Add(GenerateTableRow(TableRowSection.TableFooter, empty, empty, finalTotal));

			ReportContents.Controls.Add(table);
		}

		private Literal GenerateLiteral(string str)
		{
			return new Literal { Text = str };
		}

		private TableRow GenerateTableRow(TableRowSection rowSection, params Control[] ctrls)
		{
			var row = new TableRow { TableSection = rowSection };

			foreach (var ctrl in ctrls)
			{
				if (rowSection == TableRowSection.TableHeader)
					row.Cells.Add(GenerateTableHeaderCell(ctrl));
				else
					row.Cells.Add(GenerateTableCell(ctrl));
			}

			return row;
		}

		private TableCell GenerateTableCell(Control ctrl)
		{
			var cell = new TableCell();

			cell.Controls.Add(ctrl);

			return cell;
		}

		private TableHeaderCell GenerateTableHeaderCell(Control ctrl)
		{
			var cell = new TableHeaderCell();

			cell.Controls.Add(ctrl);

			return cell;
		}
	}
}